
import CoreLocation
import Flutter
 
class LocationManager: NSObject {
    let locationManager = CLLocationManager()
    private let channel: FlutterMethodChannel
    
    init(channel:FlutterMethodChannel) {
        self.channel = channel
    }
 
    func startLocationUpdates() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.startUpdatingLocation()
    }
    
    
    func stopLocationUpdates() {
        locationManager.stopUpdatingLocation()
    }
}
 
// 实现CLLocationManagerDelegate协议
extension LocationManager: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        
        guard let location = locations.last else { return }
        
        
        // 1. 组装位置信息字典（确保所有值都符合 JSON 格式要求）
        let locationData: [String: Any] = [
            // 经纬度
            "latitude": location.coordinate.latitude,
            "longitude": location.coordinate.longitude,
            // 精度
            "horizontalAccuracy": location.horizontalAccuracy,
            // 海拔
            "altitude": location.altitude,
            "verticalAccuracy": location.verticalAccuracy,
            // 时间戳
            "timestamp": location.timestamp.timeIntervalSince1970,
            // 速度与航向（可选）
            "speed": location.speed,
            "course": location.course,
            // 楼层（可选，可能为nil）
            "floor": location.floor?.level ?? NSNull() // 用 NSNull 表示 JSON 中的 null
        ]
        
        // 2. 转换为 JSON 数据
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: locationData, options: [])
            
            // 3. 转换为 JSON 字符串（可选，根据需要选择数据类型）
            if let jsonString = String(data: jsonData, encoding: .utf8) {
                channel.invokeMethod("locationServiceCallback", arguments: jsonString)
            } else {
                print("JSON 数据转字符串失败")
            }
        } catch {
            print("JSON 序列化失败: \(error.localizedDescription)")
        }
    }
}
